package com.bjgraphite.report.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.HMacJWTSigner;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class JWTTokenUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(JWTTokenUtils.class);

    public static JWTSigner jwtSigner = new HMacJWTSigner("HMACSHA512", "jhtt#$%^&!)09".getBytes());


    public static String getJwtToken(Long expireTime, JWTSigner jwtSigner) {
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        map.put("sub", "jhtt");
//        map.put("exp", System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 7));
        map.put("exp", System.currentTimeMillis() + (expireTime));
        String token = JWTUtil.createToken(map, jwtSigner);
        return token;
    }

    public static Boolean checkToken(String jwtToken, JWTSigner jwtSigner) {
        boolean verify = JWTUtil.verify(jwtToken, jwtSigner);
        if(!verify){
            return false;
        }
        JWT jwt = JWTUtil.parseToken(jwtToken);
        Long expTime = jwt.getPayload().getClaimsJson().getLong("exp");
        Date date = new Date();
        if (date.getTime() > expTime) {
            return false;
        }
        return true;
    }
}
